package util

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"log"
)

//func main() {
//	origin_data := `{"total":1,"stationStatusInfo":{"operationID":"123456789","stationID":"111111111111111","connectorStatusInfos":{"connectorID":1,"equipmentID":"10000000000000000000001","status":4,"currentA":0,"currentB":0,"currentC":0,"voltageA":0,"voltageB":0,"voltageC":0,"soc":10}}}`
//	aesKey := "1234567890abcdef"
//	aesIv := "1234567890abcdef"
//
//	txt, err := AESBase64Encrypt(origin_data, aesKey, aesIv)
//	if err != nil{
//		log.Println(err)
//		return
//	}
//	log.Println(txt)
//	var source string
//	source, err = AESBase64Decrypt(txt, aesKey, aesIv)
//	if err != nil{
//		log.Println(err)
//	}
//	log.Println(source)
//}

func AESBase64Encrypt(origin_data []byte, key string, ivStr string) (base64_result string, err error) {
	//iv := []byte{1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6}
	iv := []byte(ivStr)
	var block cipher.Block
	if block, err = aes.NewCipher([]byte(key)); err != nil {
		log.Println(err)
		return
	}
	encrypt := cipher.NewCBCEncrypter(block, iv)
	var source []byte = PKCS5Padding(origin_data, 16)
	var dst []byte = make([]byte, len(source))
	encrypt.CryptBlocks(dst, source)
	base64_result = base64.StdEncoding.EncodeToString(dst)
	return
}

func AESBase64Decrypt(encrypt_data string, key string, ivStr string) (origin_data []byte, err error) {
	//iv := []byte{1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6}
	iv := []byte(ivStr)
	var block cipher.Block
	if block, err = aes.NewCipher([]byte(key)); err != nil {
		log.Println(err)
		return
	}
	encrypt := cipher.NewCBCDecrypter(block, iv)

	var source []byte
	if source, err = base64.StdEncoding.DecodeString(encrypt_data); err != nil {
		log.Println(err)
		return
	}
	var dst []byte = make([]byte, len(source))
	encrypt.CryptBlocks(dst, source)
	origin_data = PKCS5Unpadding(dst)
	return
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5Unpadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
